package com.wenx.webservicecamel;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.wenx.beancamel.HelloBean;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultMessage;
import org.apache.cxf.message.MessageContentsList;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultText;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URLDecoder;
import java.util.*;
import java.util.logging.XMLFormatter;

public class AppWebServicePub extends RouteBuilder {

    public static void main(String[] args) throws Exception {

        CamelContext context = new DefaultCamelContext(); // 1. 创建 CamelContext.
        context.addRoutes(new AppWebServicePub());
        context.setTracing(true);
        context.start(); // 4. 启动CamelContext.
        Thread.sleep(Integer.MAX_VALUE);  // 为了保持CamelContext处于工作状态，这里需要sleep主线程
        context.stop(); // 最后停止CamelContext
    }

    /**
     * 生产消费   webservice---camel---webservice
     * @throws Exception
     */
    public void configure() throws Exception {
        String content="<?xml version=\"1.0\" encoding=\"utf-8\"?>  <soap:Envelope"
                + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<soap:Body> " +
                "        <m:sayHello xmlns:m=\"http://webservice.web.comp.com/\"> " +
                "            <id>123</id>  " +
                "            <name>张三</name>  " +
                "        </m:sayHello> " +
                "    </soap:Body> "
                + "</soap:Envelope>";
    	from("timer:foo?repeatCount=1")
                .setHeader(Exchange.CHARSET_NAME,constant("UTF-8"))
        .setBody(constant(content))             //set request body
                .to("cxf:"
                + "http://localhost:8088/services/demo" //service address
                + "?"
                + "wsdlURL=http://localhost:8088/services/demo?wsdl"    //wsdl url
 /*                       + "&"
                        + "serviceClass=service.wenx.com/WebServiceImpl"*/
                + "&"
                + "dataFormat=RAW"        //dataformat type
        )
               .setHeader(Exchange.CHARSET_NAME,constant("utf-8"))
        .convertBodyTo(String.class)
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        String objxml = exchange.getIn().getBody().toString();
//                        int returns = objxml.indexOf("<return>");
//                        int end = objxml.indexOf("</return>");
//                        int start = returns+"<return>".length();
//                        String value = objxml.substring(start,end);
//                        System.out.println("生产的body="+value);
                        List<String> list = parseSoap(objxml);
                        Object mapList = null;

//                        if(value!=null || !"".equals(value)){
//                            ReadContext context = JsonPath.parse(value);
//                            mapList =
//                                    context.read("$.data.[?(@.name == 'lisi')]");
//                        }

                        String content="<?xml version=\"1.0\" encoding=\"utf-8\"?>  <soap:Envelope"
                                + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                                + "<soap:Body> " +
                                "        <m:welcome xmlns:m=\"http://webservice.web.comp.com/\"> " +
                                "            <data>aa</data>  " +
                                "        </m:welcome> " +
                                "    </soap:Body> "
                                + "</soap:Envelope>";
                        exchange.getOut().setBody(content);
                    }
                })
        .to("cxf:"
                        + "http://localhost:8088/services/demo" //service address
                        + "?"
                        + "wsdlURL=http://localhost:8088/services/demo?wsdl"    //wsdl url
                        + "&"
                        + "dataFormat=RAW"        //dataformat type
        );
    }

    /*解析soap内容,返回字符串列表*/
    public List<String> parseSoap(String b) throws DocumentException {
        Document doc = DocumentHelper.parseText(b);
        List list = doc.selectNodes("//text()");
        List<String> res = new ArrayList<String>();
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            DefaultText te = (DefaultText) iterator.next();
            System.out.println(trimText(te.getText()));
            res.add(trimText(te.getText()));
        }
        return res;
    }
    /*把返回值中的空格去掉*/
    private static String trimText(String text) {
        StringBuffer textContent = new StringBuffer();
        StringTokenizer tokenizer = new StringTokenizer(text);
        while (tokenizer.hasMoreTokens()) {
            String str = tokenizer.nextToken();
            textContent.append(str);

            if (tokenizer.hasMoreTokens()) {
                textContent.append(" "); // separator
            }
        }
        return textContent.toString();
    }
}
